package com.itheima.controller;

import com.alibaba.dubbo.config.annotation.Reference;

import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.entity.Result;
import com.itheima.pojo.FoodLibrary;
import com.itheima.service.FoodLibraryService;

import com.itheima.untils.POIUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("/food")
public class FoodLibraryController {
    @Reference
    private FoodLibraryService foodLibraryService;

    @RequestMapping("/upload")
    public Result upload(@RequestParam(name = "excelFile") MultipartFile multipartFile){
        try {
            List<String[]> list = POIUtils.readExcel(multipartFile);
            List<FoodLibrary> foodLibraryList = new ArrayList<>();
            if(list!=null && list.size()>0){
                for (String[] strings : list) {

                    FoodLibrary foodLibrary = new FoodLibrary(null,strings[0],strings[1],strings[2]);
                    foodLibraryList.add(foodLibrary);
                }
                foodLibraryService.add(foodLibraryList);
            }else {
                throw new RuntimeException("表格数据转换失败!");
            }
            return new Result(true, "插入成功");
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, "失败了");
        }
    }
    @RequestMapping("/findPage")
    public PageResult findPage(@RequestBody QueryPageBean queryPageBean){
        return foodLibraryService.findPage(queryPageBean);
    }

    @RequestMapping("/findAll")
    public Result findAll(){
        try {
            List<FoodLibrary> foodLibraryList = foodLibraryService.findAll();
            return new Result(true,"查询成功");
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,"查询失败");
        }
    }
    @RequestMapping("/insert")
    public Result insert(@RequestBody FoodLibrary foodLibrary){
        try {
            foodLibraryService.insert(foodLibrary);
            return new Result(true,"改好了");
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,"失败了");
        }
    }
}
